<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    top="25px"
    :close-on-click-modal="false"
    :append-to-body="true"
    style="min-width: 900px;"
    @close="dialogClose"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName') + ':'">
        <el-input
          v-model.trim="prodName"
          style="width: 200px;"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings') + ':'">
        <el-cascader
          v-model="selectedCategory"
          :options="categoryList"
          :props="categoryTreeProps"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          type="primary"
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t('order.query') }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t('temp.setNull') }}
        </div>
      </el-form-item>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="table-row"
        :row-key="getRowKeys"
        style="width: 100%"
        height="580"
        @selection-change="selectChangeHandle"
      >
        <el-table-column
          v-if="props.isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.prodId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!props.isSingle"
          type="selection"
          header-align="center"
          align="center"
          :reserve-selection="true"
          width="50"
        />
        <el-table-column
          width="140"
          :label="$t('product.pic')"
        >
          <template #default="scope">
            <ImgShow
              :src="scope.row.pic"
              width="60"
              height="60"
              :alt="scope.row.prodName"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="prodName"
          :label="$t('product.prodName')"
        />
        <el-table-column
          prop="price"
          :label="$t('components.commodityPrice')"
          width="200px"
        />
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <template #footer>
      <span>
        <span
          class="default-btn"
          @click="cancelFn"
        >{{ $t('crud.filter.cancelBtn') }}</span>
        <span
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </span>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { treeDataTranslate, idList } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
const emit = defineEmits(['refreshSelectProds', 'refreshSelectProds', 'refreshSelectProds'])

const visible = ref(false)
const dataForm = reactive({
  product: ''
})
const singleSelectProdId = ref(0)
const prodName = ref('')
const selectProds = ref([])
const dataList = ref([])
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dataListLoading = ref(false)
const dataListSelections = ref([])
const categoryList = ref([])
const selectedCategory = ref([])
const categoryTreeProps = ref({
  value: 'categoryId',
  label: 'categoryName',
  expandTrigger: 'hover'
})
const categoryId = ref()
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  prodType: {
    default: undefined,
    type: Number
  },
  dataUrl: {
    default: '/prod/prod/page',
    type: String
  }
})
const prodTableRef = ref(null)
onActivated(() => {
  getDataList()
})

// 获取数据列表
const init = selectProd => {
  singleSelectProdId.value = 0
  selectProds.value = selectProd
  page.value.currentPage = 1
  clean()
  visible.value = true
  dataListLoading.value = true
  getDataList()
  getCategoryList()
}
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2,
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: page.value.currentPage,
          size: page.value.pageSize,
          prodName: prodName.value || null,
          categoryId: categoryId.value || null,
          status: 1,
          prodType: props.prodType === 0 ? 0 : undefined
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    dataListLoading.value = false
    if (selectProds.value) {
      nextTick(() => {
        selectProds.value.forEach(row => {
          const index = dataList.value.findIndex(prodItem => prodItem.prodId === row.prodId)
          if (index !== -1) {
            prodTableRef.value.toggleRowSelection(dataList.value[index], true)
          }
        })
      })
    }
  })
}
// 每页数
const onPageSizeChange = val => {
  page.value.pageSize = val
  page.value.currentPage = 1
  getDataList()
}
// 当前页
const onPageChange = val => {
  page.value.currentPage = val
  getDataList()
}
// 单选商品事件
const getSelectProdRow = row => {
  dataListSelections.value = [row]
}
// 多选点击事件
const selectChangeHandle = selection => {
  dataListSelections.value = selection
}
const getRowKeys = row => {
  return row.prodId
}
/**
 * 获取分类id
 */
const handleChange = val => {
  categoryId.value = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  page.value.currentPage = 1
  getDataList()
}
const cancelFn = () => {
  visible.value = false
  dataListSelections.value = false
  prodTableRef.value?.clearSelection()
}
const dialogClose = () => {
  prodTableRef.value?.clearSelection()
}
/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  categoryId.value = null
  selectedCategory.value = idList(
    categoryList.value,
    categoryId.value,
    'categoryId',
    'children'
  ).reverse()
}
// 确定事件
const submitProds = () => {
  const prods = []
  dataListSelections.value.forEach(item => {
    const prodIndex = prods.findIndex(prod => prod.prodId === item.prodId)
    if (prodIndex === -1) {
      prods.push({
        prodId: item.prodId,
        prodName: item.prodName,
        pic: item.pic,
        groupActivityId: item.groupActivityId,
        seckillActivityId: item.seckillActivityId,
        activityId: item.activityId,
        prodType: item.prodType
      })
    }
  })
  let msgInfo = ''
  // 秒杀活动选择商品的提示
  if (props.dataUrl.includes('canSekcillProdPage')) {
    msgInfo = $t('components.seckillWhetherToContinue')
  } else if (props.dataUrl.includes('getNotGroupProdPage')) {
    // 拼团活动选择商品的提示
    msgInfo = $t('components.groupWhetherToContinue')
  }
  if (msgInfo !== '' && msgInfo !== null) {
    prodIsSeckill(prods, msgInfo)
  } else {
    if (!prods || !prods.length) {
      ElMessage.error($t('marketing.pleaseSelectAProduct'))
      return
    }
    prodTableRef.value?.clearSelection()

    emit('refreshSelectProds', prods)
    dataListSelections.value = []
    visible.value = false
  }
}
/**
 * 查询商品是否在参与秒杀活动
 */
const prodIsSeckill = (prods, msgInfo) => {
  const prodIds = []
  for (let index = 0; index < prods.length; index++) {
    prodIds.push(prods[index].prodId)
  }
  http({
    url: http.adornUrl('/admin/discount/prodIsDiscount'),
    method: 'post',
    data: prodIds
  }).then(({ data }) => {
    const msg = data
    if (msg !== undefined && msg !== null && msg !== '') {
      ElMessageBox.confirm(msgInfo, $t('weixin.tips'), {
        confirmButtonText: $t('crud.filter.submitBtn'),
        cancelButtonText: $t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        emit('refreshSelectProds', prods)
        dataListSelections.value = []
        visible.value = false
      })
    } else {
      emit('refreshSelectProds', prods)
      dataListSelections.value = []
      visible.value = false
    }
  })
}
defineExpose({ init })
</script>
<style scoped>
.prods-select-body {
  border-top: 1px solid #eeeeee;
  border-right: 1px solid #eeeeee;
  border-left: 1px solid #eeeeee;
}
.pagination-box{
  padding-top: 20px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}
</style>
